package com.ctos.controller;

import com.ctos.common.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传 和 下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upDownload(MultipartFile file) throws IOException {

        //先判断 要存放的目录是否存在 不存在则创建一个
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }

        //原始id
        String originalFilename = file.getOriginalFilename();
        //获取原始id的后缀 包括.
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用uuid生成文件名 防止覆盖
        String fileName = UUID.randomUUID()+suffix;

        file.transferTo(new File(basePath+fileName));


        return Result.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //文件输入流 获取文件
        FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

        //文件输出流 写回到浏览器
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/jpeg");

        IOUtils.copy(fileInputStream, outputStream);

        fileInputStream.close();
        outputStream.close();
    }

}
